package cn.lysj.framework.elm.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.lysj.framework.base.BaseService;
import cn.lysj.framework.common.exception.MyException;
import cn.lysj.framework.common.utils.json.JacksonUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.elm.base.ElmContent;
import cn.lysj.framework.elm.domain.ElmFoodDetail;
import cn.lysj.framework.elm.domain.ElmOrder;
import cn.lysj.framework.elm.domain.FoodReleveEleme;
import cn.lysj.framework.elm.elmenum.ElmOrderStatus;
import cn.lysj.framework.elm.elmenum.ElmOrderWay;
import cn.lysj.framework.elm.elmenum.ElmPrint;
import cn.lysj.framework.elm.repository.ElmFoodDetailRepository;
import cn.lysj.framework.elm.repository.ElmOrderRepository;
import cn.lysj.framework.foodv2.domain.Food;
import cn.lysj.framework.foodv2.repository.FoodRepository;
import cn.lysj.framework.pirpraph.domain.FoodReport;
import cn.lysj.framework.pirpraph.repository.FoodReportRepository;
import eleme.openapi.sdk.api.entity.order.OGroupItemAttribute;
import eleme.openapi.sdk.api.entity.order.OGroupItemSpec;
import eleme.openapi.sdk.api.entity.order.OOrder;
import eleme.openapi.sdk.api.exception.ServiceException;
import eleme.openapi.sdk.api.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.OrderedMap;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author drj
 * @description 饿了么订单服务层
 * @create 2019-01-21 16:35:47
 **/
@Slf4j
@Service
@Transactional
public class ElmOrderService implements BaseService<ElmOrder> {

    @Resource
    private ElmOrderRepository elmOrderRepository;

    @Resource
    private ElmFoodDetailRepository elmFoodDetailRepository;
    @Resource
    private FoodReportRepository foodReportRepository;
    @Resource
    private FoodRepository foodRepository;

    @Override
    public ElmOrderRepository getRepository() {
        return elmOrderRepository;
    }

    @Resource
    private ElmContent elemeContent;

    /*
     * @author drj
     * @date 2019-01-23 14:32
     * @Description :同步饿了么平台的订单
     */
    public ElmOrder getElmOrder(String orderNumber, String storeId) throws ServiceException {
        if (null == elemeContent.cash_token) {
            elemeContent.cash_token = elemeContent.client.getTokenByCode(elemeContent.authcode, elemeContent.redirect_url);
        }
        if (null == elemeContent.cash_token.getRefreshToken()) {
            elemeContent.cash_token = elemeContent.client.getTokenByRefreshToken(elemeContent.cash_token.getRefreshToken());
        }
        //获取饿了么对应的APPKEY,APPSECRET

        OrderService orderService = new OrderService(elemeContent.config, elemeContent.cash_token);
        OOrder oOrder = orderService.getOrder(orderNumber);
        log.info("订单信息"+oOrder.toString());
        ElmOrder elmOrder = new ElmOrder();
        CopyOptions copyOptions = new CopyOptions();
        copyOptions.setIgnoreNullValue(true);
        BeanUtil.copyProperties(oOrder, elmOrder, copyOptions);
        List list = oOrder.getGroups();
        List<ElmFoodDetail> elmFoodDetails = new LinkedList<>();
        String foodDetail = "";
        for (Object o : list) {
            Map map1 = JacksonUtil.toObjectMap(JacksonUtil.toJson(o));
            List items = (List) map1.get("items");
            for (Object item : items) {
                Map m = JacksonUtil.toObjectMap(JacksonUtil.toJson(item));
                //构建菜品关系表
                ElmFoodDetail elmFoodDetail = new ElmFoodDetail();
                elmFoodDetail.setElmeOrderNumber(orderNumber);
                elmFoodDetail.setElmFoodId(String.valueOf(m.get("vfoodId")));
                elmFoodDetail.setFoodName(String.valueOf(m.get("name")));
                elmFoodDetail.setQuantity(Double.parseDouble(String.valueOf(m.get("quantity"))));
                elmFoodDetail.setTotal(Double.parseDouble(String.valueOf(m.get("total"))));
                String newSpecs = "";
                //规格
                List oGroupItemSpecs = (List) m.get("newSpecs");
                // 属性
                List attributes = (List) m.get("attributes");
                for (Object oGroupItemSpec : oGroupItemSpecs) {
                    Map oGroupItemSpecMap = JacksonUtil.toObjectMap(JacksonUtil.toJson(oGroupItemSpec));
                    newSpecs += (String) oGroupItemSpecMap.get("value") + "+";
                }
                for (Object attribute : attributes) {
                    Map attributeMap = JacksonUtil.toObjectMap(JacksonUtil.toJson(attribute));
                    newSpecs += attributeMap.get("value") + "+";
                }
                elmFoodDetail.setSpecAndAttr(newSpecs);
                elmFoodDetails.add(elmFoodDetail);
                //构造订单详情,在后台订单显示
                foodDetail += elmFoodDetail.getFoodName() + " x " + elmFoodDetail.getQuantity() + " ;";
            }
        }
        elmOrder.setDetail(foodDetail);
        elmOrder.setOrderNumber(orderNumber);
        elmOrder.setStoreId(storeId);
        elmFoodDetailRepository.save(elmFoodDetails); //保存菜品信息
        elmOrder.setPrint(ElmPrint.UNDEFINE.getCode());
        elmOrder.setOrderStatus(ElmOrderWay.MANUALORDER.getCode()); //根据接单方式设置相应的订单状态
        elmOrder = elmOrderRepository.saveAndFlush(elmOrder);//保存订单信息
        elmOrder.setElmFoodDetailList(elmFoodDetails);
        return elmOrder;
    }

    /*
     * @author drj
     * @date 2019-01-24 14:47
     * @Description :手动接单
     */
    public Resp manualOrder(String elmOrderId) {
        if (ParamUtil.isBlank(elmOrderId)) {
            throw new MyException("参数错误");
        }
        ElmOrder elmOrder = elmOrderRepository.findOne(elmOrderId);
        if (null == elmOrder) {
            throw new MyException("未知错误");
        }
        List<ElmFoodDetail> elmFoodDetailList = elmFoodDetailRepository.findByElmeOrderNumber(elmOrder.getOrderNumber());
        //菜品报表信息
        for (ElmFoodDetail elmFoodDetail : elmFoodDetailList) {
            FoodReleveEleme foodReleveEleme = elemeContent.foodRelevElemeService.getRepository().findByElemeFoodId(elmFoodDetail.getElmFoodId());
            //若没设置过关联关系则跳过
            if (ParamUtil.isBlank(foodReleveEleme)) {
                break;
            }
            FoodReport foodReport = foodReportRepository.findByFoodId(foodReleveEleme.getPlatFormFoodId());
            //如果之前没该菜品的报表信息则生成一个
            if (ParamUtil.isBlank(foodReport)) {
                foodReport = new FoodReport();
                foodReport.setStoreId(foodReleveEleme.getStoreId());
                foodReport.setFoodId(foodReleveEleme.getPlatFormFoodId());
                Food food = foodRepository.findOne(foodReleveEleme.getPlatFormFoodId());
                foodReport.setFoodName(food.getName());
                foodReport.setPlatNumber(0);
                foodReport.setElmNumber(0);
                foodReport.setMtNumber(0);
            }
            foodReport.setElmNumber(foodReport.getElmNumber() + new Double(elmFoodDetail.getQuantity()).intValue());
            foodReportRepository.save(foodReport);
        }
        //改变订单状态
        elmOrder.setElmFoodDetailList(elmFoodDetailList);
        elmOrder.setOrderStatus(ElmOrderStatus.ACCECPT.getCode());
        elmOrder.setPrint(ElmPrint.UNPRINT.getCode());
        elmOrder.setCreateTime(new Date());
        elmOrderRepository.save(elmOrder);
        //调用改变饿了么平台订单状态
        if (null == elemeContent.cash_token) {
            throw new MyException("未知错误");
        }
        if (null == elemeContent.cash_token.getRefreshToken()) {
            elemeContent.cash_token = elemeContent.client.getTokenByRefreshToken(elemeContent.cash_token.getRefreshToken());
        }
        OrderService orderService = new OrderService(elemeContent.config, elemeContent.cash_token);
        try {
            orderService.confirmOrderLite(elmOrder.getOrderNumber());
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        }
        return new Resp("操作成功");
    }


    /*
     * @author drj
     * @date 2019-01-23 14:37
     * @Description ：同意退款
     */
    public Resp agreeRefund(String elmOrderId) {

        if (ParamUtil.isBlank(elmOrderId)) {
            return new Resp(Resp.PARAM_ERROR, "参数错误");
        }
        ElmOrder elmOrder = elmOrderRepository.findOne(elmOrderId);
        if (null == elmOrder) {
            return new Resp(Resp.PARAM_ERROR, "未知错误");
        }
        //已经退过款,则提示已经处理过
        if (ElmOrderStatus.AGREE.getCode().equals(elmOrder.getOrderStatus())) {
            return new Resp(Resp.PARAM_ERROR, "请勿重复操作");
        }

        if (null == elemeContent.cash_token) {
            throw new MyException("未知错误");
        }
        if (null == elemeContent.cash_token.getRefreshToken()) {
            elemeContent.cash_token = elemeContent.client.getTokenByRefreshToken(elemeContent.cash_token.getRefreshToken());
        }
        //调用饿了么平台退单接口
        OrderService orderService = new OrderService(elemeContent.config, elemeContent.cash_token);
        try {
            orderService.agreeRefundLite(elmOrder.getOrderNumber());
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        }
        //改变订单状态
        elmOrder.setOrderStatus(ElmOrderStatus.AGREE.getCode());
        elmOrderRepository.saveAndFlush(elmOrder);
        //删减菜品信息
        List<ElmFoodDetail> elmFoodDetailList = elmFoodDetailRepository.findByElmeOrderNumber(elmOrder.getOrderNumber());
        List<FoodReport> foodReportList = new LinkedList<>();
        for (ElmFoodDetail elmFoodDetail : elmFoodDetailList) {
            FoodReleveEleme foodReleveEleme = elemeContent.foodRelevElemeService.getRepository().findByElemeFoodId(elmFoodDetail.getElmFoodId());
            if (null == foodReleveEleme) {
                break;
            }
            FoodReport foodReport = foodReportRepository.findByFoodId(foodReleveEleme.getPlatFormFoodId());
            foodReport.setElmNumber(foodReport.getElmNumber() - new Double(elmFoodDetail.getQuantity()).intValue());
            foodReportList.add(foodReport);
        }
        foodReportRepository.save(foodReportList);
        return new Resp("操作成功");
    }

    /*
     * @author drj
     * @date 2019-01-24 14:46
     * @Description ：拒绝退款
     */
    public Resp disagreeRefund(String elmOrderId) {
        if (ParamUtil.isBlank(elmOrderId)) {
            return new Resp(Resp.PARAM_ERROR, "参数错误");
        }
        ElmOrder elmOrder = elmOrderRepository.findOne(elmOrderId);
        if (null == elmOrder) {
            return new Resp(Resp.PARAM_ERROR, "未知错误");
        }
        elmOrder.setOrderStatus(ElmOrderStatus.DISAGREE.getCode());
        if (null == elemeContent.cash_token) {
            throw new MyException("未知错误");
        }
        if (null == elemeContent.cash_token.getRefreshToken()) {
            elemeContent.cash_token = elemeContent.client.getTokenByRefreshToken(elemeContent.cash_token.getRefreshToken());
        }
        OrderService orderService = new OrderService(elemeContent.config, elemeContent.cash_token);
        try {
            orderService.disagreeRefundLite(elmOrder.getOrderNumber(), "拒绝退款");
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new MyException(e.getMessage());
        }
        return new Resp("操作成功");
    }


}